<template>
	<div class="login">
		<el-form :model="user" class="demo-ruleForm" label-position="right" label-width="70px" status-icon  :rules="myrules" :hide-required-asterisk="true" ref="formRef">
			<el-card class="box-card">
				<template #header>
				  <div class="card-header">
					<span><h3>欢迎您登录公众监督系统</h3></span>
				  </div>
				</template>
				<el-form-item label="手机号：" prop="phone">
					<el-input v-model="user.phone" placeholder="请输入手机号"/>
				</el-form-item>
				<el-form-item label="密码：" prop="password">
					<el-input v-model="user.password" type="password" placeholder="请输入密码"/>
				</el-form-item>
				<el-form-item label="注册" @click="register"></el-form-item>
				<el-button type="primary" @click="login" plain>登录</el-button>
			</el-card>
		</el-form>
	</div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import axios from 'axios';
// import axios from '../../axios';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import JSEncrypt from 'jsencrypt'; // 导入 jsencrypt 库
import Qs from 'qs'
const router = useRouter();
const route = useRoute();
const querydata = route.query;

const user = ref({
  phone: '',
  password: ''
});

const myrules = {
  phone: [
    {
      required: true,
      trigger: 'blur',
      message: '用户名不能为空'
    }
  ],
  password: [
    {
      required: true,
      trigger: 'blur',
      message: '密码为必填项'
    }
  ]
};

const formRef = ref(null);



const login = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 创建一个新的 JSEncrypt 实例
        const encryptor = new JSEncrypt();
		//获取公钥
		const publicKey= await getRSAPublicKey();
		console.log(publicKey)
        // 设置公钥，这里假设 publicKey 是你的 RSA 公钥字符串
        encryptor.setPublicKey(publicKey);
        // 加密密码
		const encryptedpassword1 = encodeURIComponent(encryptor.encrypt(user.value.password));
		const encryptedusername1 = encodeURIComponent(encryptor.encrypt(user.value.phone));

		let data=Qs.stringify({
			encryptedUsername: encryptedusername1,
			encryptedPassword: encryptedpassword1,
		  })
		  let dataJson={
			encryptedUsername: encryptedusername1,
			encryptedPassword: encryptedpassword1,
		  }
		  console.log(dataJson)
		// 发送 POST 请求
		const response = await axios.post('http://localhost:7000/service-supervisor/supervisor/svLogin', dataJson);
        const result = ref(response.data)
		localStorage.setItem('token',result.value.sendResult)
        if (result.value.code === 0) {
          ElMessage.success('登录成功!');
          router.push({
            path: '/supervisor/selectgrid',
            query: {
              token: result.sendResult
            }
          });
        } else {
          console.error(result);
          ElMessage.error(result.msg);
        }
      } catch (error) {
        console.error('Login failed:', error);
      }
    }
  });
};

// onMounted( async()=>{
// 	const publicKey=  await getRSAPublicKey();
// 	console.log(publicKey)
// })
const getRSAPublicKey = async () => {
  try {	  
    const response = await axios.get('http://localhost:7000/service-admin/auth/public-key');
    return response.data;
  } catch (error) {
    console.error('Failed to fetch RSA public key:', error);
    throw error;
  }
};

const register=()=>{
	router.push({
		path:'/supervisor/register',
	})
}
</script>

<style>
	.login{
		height: 100vh;
		display:flex;
		flex-direction: column;
		justify-content:center;
		align-items: center;
		background-color: gray;
	}
	.demo-ruleForm {
		
		display: flex;
		justify-content: center; 
		align-items: center; 
		height: 80vh; 
	  
	}
	

</style>